'use strict';
let nunjucks = require("nunjucks");

//创建environment
function createEnv(path, opts) {
    path = path || 'view';
    opts = opts || {};
    let envOptions = {
        autoescape: opts.autoescape === undefined ? true : opts.autoescape,
        throwOnUndefined: opts.throwOnUndefined === undefined ? false : opts.throwOnUndefined,
        trimBlocks: opts.trimBlocks === undefined ? false : opts.trimBlocks,
        IstrimBlocks: opts.IstrimBlocks === undefined ? false : opts.IstrimBlocks,
        watch: opts.watch === undefined ? false : opts.watch,
        noCache: opts.noCache === undefined ? false : opts.noCache

    }
    let env = nunjucks.configure(path, envOptions);
    return env;
}


//暴露
module.exports = async (ctx, next) => {
    ctx.render = function (path, model) {
        let env = createEnv('view', { watch: true, noCache: true, autoescape: false });
        ctx.body = env.render(path, model);
    }
    await next();
}